package com.bsoft.gol.hbs.bbpmessagel.util;

import com.alibaba.fastjson.JSONObject;
import ctd.net.rpc.json.JSONResponseBean;
import hcn.util.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @description:微信公众号消息API工具类
 * @date: 2019/3/25 16:23
 */
public class WeChatMessageApiUtil {

    protected static final Logger log = LoggerFactory.getLogger(WeChatMessageApiUtil.class);

    /**
     * 连接请求微信后台接口
     *
     * @param action 接口url
     * @param json   请求接口传送的json字符串
     */
    private static JSONResponseBean connectWeiXinInterface(String action, String json) {
        JSONResponseBean baseResponse = new JSONResponseBean();
        try {
            URL url = new URL(action);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            OutputStream os = http.getOutputStream();
            log.info("请求入参:{}", json);
            os.write(json.getBytes("UTF-8"));// 传入参数
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String result = new String(jsonBytes, "UTF-8");
            log.info("请求返回结果:{}", result);
            os.flush();
            os.close();
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (null != jsonObject && jsonObject.containsKey("errcode") && jsonObject.getInteger("errcode") == 0) {
                baseResponse.setCode(ResultCode.SUCCESS);
                baseResponse.setMsg("微信公众号消息推送成功");
            } else {
                baseResponse.setCode(ResultCode.ERROR);
                if (null != jsonObject) {
                    baseResponse.setMsg(jsonObject.getString("errmsg"));
                } else {
                    baseResponse.setMsg("微信公众号消息推送失败");
                }
            }
        } catch (Exception e) {
            log.error("微信公众号消息推送失败：", e);
            baseResponse.setCode(ResultCode.ERROR);
            baseResponse.setMsg("微信公众号消息推送失败：" + e.getMessage());
        }
        return baseResponse;
    }


    /**
     * @param jsonString  请求接口传送的json字符串
     * @param accessToken
     * @return
     * @description: 发送模板消息给单个用户
     */
    public static JSONResponseBean sendTemplateMessage(String jsonString, String accessToken) {
//        示例jsonString
//        注意：不同模板有差别，请根据具体模板组装JSON字符串
//        {
//            "touser":"OPENID",
//                "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
//                "url":"http://weixin.qq.com/download",
//            "data":{
//            "first": {
//                "value":"恭喜你购买成功！",
//                        "color":"#173177"
//            },
//            "keyword1":{
//                "value":"巧克力",
//                        "color":"#173177"
//            },
//            "keyword2": {
//                "value":"39.8元",
//                        "color":"#173177"
//            },
//            "keyword3": {
//                "value":"2014年9月22日",
//                        "color":"#173177"
//            },
//            "remark":{
//                "value":"欢迎再次购买！",
//                        "color":"#173177"
//            }
//        }
//        }
        String action = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        return connectWeiXinInterface(action, jsonString);
    }

    /**
     * @param jsonString  请求接口传送的json字符串
     * @param accessToken
     * @return
     * @description: 发送文本消息给单个用户
     */
    public static JSONResponseBean sendtextMessageToUser(String jsonString, String accessToken) {
//        示例jsonString
//        {
//            "touser":"OPENID",
//                "msgtype":"text",
//                "text":
//            {
//                "content":"Hello World"
//            }
//        }
        String action = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
        return connectWeiXinInterface(action, jsonString);
    }

    /**
     * @param jsonString  请求接口传送的json字符串
     * @param accessToken
     * @return
     * @description: 发送小程序订阅消息给单个用户
     */
    public static JSONResponseBean sendMiniSubscribeMessage(String jsonString, String accessToken) {
        String action = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
        return connectWeiXinInterface(action, jsonString);
    }

    /**
     * @param jsonString  请求接口传送的json字符串
     * @param accessToken
     * @return
     * @description: 发送统一服务消息
     */
    public static JSONResponseBean sendUniformMessage(String jsonString, String accessToken) {
        String action =
                "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" + accessToken;
        return connectWeiXinInterface(action, jsonString);
    }

}
